<template>
  <view>
    <view v-if="total>0">
      <view v-for="(item,index) in cardList" :key="index">
        <view class="card">
          <view class="card-left">
            <view style="font-size:36rpx" v-if="item.type=='1'">月租卡</view>
            <view style="font-size:36rpx" v-if="item.type=='2'">储值卡</view>
            <view style="font-size:36rpx" v-if="item.type=='4'">免费卡</view>
            <view v-if="item.type=='1'||item.type=='4'">
              <text v-if="time[index].timeDay>0&&time[index].timeDay<10">剩余{{time[index].timeDay}}天</text>
              <text v-else-if="time[index].timeDay<0">已过期</text>
              <text v-else-if="time[index].timeDay>10&&item.status==1">正常</text>
              <text v-if="item.status==0">去激活</text>
            </view>
            <view class="rt-p3" v-if="item.type=='2'">余额:{{item.accountBalance}}</view>
          </view>
          <view class="card-right">
            <view class="rt-p1 one-line" style="font-size:28rpx">{{item.plates}}</view>
            <!-- <view class="rt-p1 one-line" v-else>{{item.plates}}</view> -->
            <view class="rt-p2">{{item.park&&item.park.parkName||"暂无车场数据"}}</view>
            <view class="rt-p3" v-if="item.type=='1'||item.type=='4'">有效期至:{{time[index].endTime}}</view>
            <view class="rt-p3" v-if="item.type=='2'">余额:{{item.accountBalance}}</view>
          </view>
          <view class="btn" @tap="goRecharge(item)" v-if="item.type=='2'">充值</view>
          <view class="btn" @tap="goRecharge(item)" v-if="item.type=='1'">{{item.status==0?'去激活':'延期续费'}}</view>
        </view>
        <view class="clear"></view>
      </view>
    </view>
    <view v-if="total==0&&!loading" class="empty">
      <image :src="imgUrl+'/empty9.png'" class="empty-img1" />
      <view class="empty-p1">暂未办卡,点击下方按钮进行购买!</view>
      <navigator url="../openCard/maps?chargType=2" hover-class="none" class="nav-box-a">
        购买储值卡
      </navigator>
      <navigator url="../openCard/maps?chargType=2" hover-class="none" class="nav-box-a">
        购买月租卡
      </navigator>
    </view>

    <!--授权手机号-->
    <view v-if="!hasPhone">
        <button
          openType="getPhoneNumber"
          @GetPhoneNumber="onGetPhoneNumber"
          class="panel-box-btn" style="width:500rpx"
        >获取手机号,查看卡券信息</button>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./card.less";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import Empty from "../../components/empty/empty";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
export default {
  data() {
    return {
      navTab: ["卡", "券"],
      currentTab: 0,
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头
      imgUrl: process.env.IOParking.IMG_URL,
      showIndex: 0,
      time: [],
      total:0,
      cardList: null,
      loading: true,
      hasPhone: false //是否授权获取手机号
    };
  },
  onLoad: function(options) {
    var that = this;
    // this.isPhone = getGlobalData("mobile") ? true : false;
    if (getGlobalData("openId")) {
      that.getCardData();
    } else {
      that.wx_login();
    }
  },

  methods: {
    wx_login() {
      var that = this;
      api
        .getUserInfo({
          scope: "all"
        })
        .then(resp => {
          if (resp.success) {
            console.log("authCode is：", resp.data);
            if (resp.data == "mock") {
              setGlobalData("openId", "oRPxj5ZrsZGRuxTa-UrzEBeLuv-s");
              //setGlobalData("mobile", "17761643218");
              that.getCardData();
              return;
            }
            that.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      var that = this;
      Taro.request({
        url: this.apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          console.log(res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            setGlobalData("openId", userOpenId);
            setGlobalData("mobile", res.data.data.phoneNum);
            that.getCardData();
            api.bury("userAuthorizationNum", {
              time: new Date().valueOf(),
              loginState: false
            });
          }
        }
      });
    },
    onGetPhoneNumber({ detail }) {
      const { encryptedData, iv } = detail;
      if (encryptedData && iv) {
        this.authPhone(encryptedData, iv);
        this.hasPhone = true;
        Taro.showLoading({
          title: "授权中，请稍后",
          mask: true
        });
      }
    },
    authPhone(encryptedData, iv) {
      var that=this
      api
        .register({
          encryptedData: encryptedData,
          iv: iv,
          scope: "all"
        })
        .then(resp => {
          Taro.hideLoading();
          if (resp.success) {
            console.log("用户注册 ", resp.data);
            if (resp.data == "mock") {
              setGlobalData("mobile", "17761643218");
              that.getCardData();
              return;
            }
            that.getInfos(resp.data);
          } else {
            console.log("err is ", resp.msg, "err code is ", resp.code);
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    getCardData: function() {
      console.log("卡券读取的信息：", {
        mobile: getGlobalData("mobile"),
        wxOpenId: getGlobalData("openId")
      });
      if(!getGlobalData("mobile")||getGlobalData("mobile")==''){
        this.cardList=[]
        this.loading=false
        this.hasPhone=false
        return
      }else{
        this.hasPhone=true
      }
      var that = this;
      var base = this.apiBaseUrl;
      that.loading = true;
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      Taro.request({
        url: base + "/parkingpayment/getparkingtoken",
        data: {
          mobile: getGlobalData("mobile"),
          wxOpenId: getGlobalData("openId")
        },
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "POST",
        success(res) {
          Taro.hideLoading();
          console.log(res.data);
          if (res.data.isSuccess) {
            if(res.data.data.length>0){
              that.total=1
            }else{
              that.total=0
            }
            that.cardList = res.data.data;
            that.loading = false;
            var times = [];
            that.cardList.map((item, index) => {
              if (item.endDate) {
                var t1 = new Date(item.endDate.replace(/-/g, "/"));
                var t2 = new Date();
                var t = new Date(t1 - t2 + 16 * 3600 * 1000);
                item.timeDay = parseInt(t.getTime() / 1000 / 3600 / 24);
                times.push({
                  timeDay: parseInt(t.getTime() / 1000 / 3600 / 24),
                  endTime: item.endDate.substring(0, 10)
                });
              } else {
                times.push({
                  timeDay: "",
                  endTime: ""
                });
              }
            });
            that.time = times;
            console.log("cardList:", that.cardList);
            console.log("time:", that.time);
          }
        }
      });
    },
    goRecharge: function(e) {
      var cardInfo = e;
      if (cardInfo.type == "1") {
        //月租卡
        if(cardInfo.status==0){//去激活
          Taro.navigateTo({
            url: "../cardManage/activateCard?cardId=" + cardInfo.id
          });
        }else{
          Taro.navigateTo({
            url: "../cardManage/monthRecharge?id=" + cardInfo.id
          });
        }
      } else if (cardInfo.type == "2") {
        Taro.navigateTo({
          url: "../cardManage/storeRecharge?id=" + cardInfo.id
        });
      }
    }
  }
};
</script>